<template>
  <el-dialog
    :title="status.isAdd ? '商品添加' : '商品编辑'"
    :visible.sync="status.isshow"
    @closed="closed"
    @opened="opened"
  >
    {{ form }}
    <el-form :model="form">
      <el-form-item label="一级分类" label-width="120px">
        <el-select
          v-model="form.first_cateid"
          placeholder="请选择一级分类"
          @change="change_first_cate_id"
        >
          <!-- 遍历数据 -->
          <el-option
            v-for="item in cateList"
            :key="item.id"
            :label="item.catename"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--二级分类 -->
      <el-form-item label="二级分类" label-width="120px">
        <el-select v-model="form.second_cateid" placeholder="请选择二级分类">
          <!-- 遍历二级分类列表 -->
          <el-option
            v-for="item in secondCateList"
            :key="item.id"
            :label="item.catename"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" label-width="120px">
        <el-input v-model="form.goodsname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="价格" label-width="120px">
        <el-input v-model="form.price" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="市场价格" label-width="120px">
        <el-input v-model="form.market_price" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="图片" label-width="120px">
        <!-- 图  3.4 封装上传图片组件-->
        <upload-img
          @getFile="form.img = $event"
          v-if="status.isshow"
          ref="upload"
        ></upload-img>
      </el-form-item>
      <!-- 3.5 规格列表: 1.从vuex中取出specsList和reqSpecsList 2.进来就发请求；3.请到的数据是分页的数据，但是此处要的是全部数据，所以修改vuex的action;4.遍历 5.修改规格，计算属性列表-->
      <el-form-item label="商品规格" label-width="120px">
        <el-select
          v-model="form.specsid"
          placeholder="请选择商品规格"
          @change="change_specs_id"
        >
          <el-option
            v-for="item in specsList"
            :key="item.id"
            :label="item.specsname"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 3.6 规格属性:1.初始化规格属性的列表attrsArr;2.商品规格变了，清空选中的属性，计算展示的属性列表；3.遍历 -->
      <el-form-item label="规格属性" label-width="120px">
        <el-select
          v-model="form.specsattr"
          placeholder="请选择规格属性"
          multiple
        >
          <el-option
            v-for="item in attrsArr"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否新品" label-width="120px">
        <el-radio v-model="form.isnew" :label="1">是</el-radio>
        <el-radio v-model="form.isnew" :label="2">否</el-radio>
      </el-form-item>
      <el-form-item label="是否热卖" label-width="120px">
        <el-radio v-model="form.ishot" :label="1">是</el-radio>
        <el-radio v-model="form.ishot" :label="2">否</el-radio>
      </el-form-item>
      <el-form-item label="商品描述" label-width="120px">
        <!-- 富文本编辑器 -->
        <div id="editor" v-if="status.isshow"></div>
      </el-form-item>

      <el-form-item label="状态" label-width="120px">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="2"
        ></el-switch>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="status.isshow = false">取 消</el-button>
      <el-button type="primary" v-if="status.isAdd" @click="add"
        >添 加</el-button
      >
      <el-button type="primary" v-else @click="updata">修 改</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  reqcatelist,
  reqgoodsadd,
  reqgoodsedit,
  reqgoodsinfo,
} from "../../../http/api";
import { successAlert ,errorAlert} from "../../../utils/alert";
import { mapGetters, mapActions } from "vuex";
import E from "wangeditor";
export default {
  components: {},
  mounted() {
    // 请求分类数据
    if (this.cateList.length == 0) {
      this.reqCateList();
    }

    //请求规格列表数据
    this.reqSpecsList(true);
  },
  props: ["status"],
  data() {
    return {
      form: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 2,
        ishot: 2,
        status: 1,
      },
      //二级分类的列表数据
      secondCateList: [],
      //规格属性的列表
      attrsArr: [],
    };
  },
  methods: {
    ...mapActions({
      //请求分类的列表
      reqCateList: "cate/reqList",
      //请求规格的列表
      reqSpecsList: "specs/reqSpecsList",
      //商品列表数据
      reqList: "goods/reqList",
    }),

    //编辑器 :弹框打开动画结束后开始创建编辑器
    opened() {
      //创建一个编辑器
      this.editor = new E("#editor");
      this.editor.create();

      //赋值
      this.editor.txt.html(this.form.description);
    },

    //修改了一级分类的id
    change_first_cate_id() {
      //选中的二级分类要重置
      this.form.second_cateid = "";

      //根据一级分类的id获取二级分类的列表
      this.requst_second_cate_list();
    },
    async requst_second_cate_list() {
      //根据一级分类的id获取二级分类的列表
      let res = await reqcatelist({ pid: this.form.first_cateid });
      if (res.data.code == 200) {
        this.secondCateList = res.data.list ? res.data.list : [];
      }
    },

    //修改了商品规格
    change_specs_id() {
      //先清空选中的属性值
      this.form.specsattr = [];

      this.computed_show_attr();
    },
    computed_show_attr() {
      //form.specsid=9
      //specsList=[{id:7,attrs:[]},{id:8,attrs:[]}]
      let obj = this.specsList.find((item) => item.id == this.form.specsid); // {}  ,undefined
      //给属性列表赋值
      this.attrsArr = obj ? obj.attrs : [];
    },

    //点了取消
    cancel() {
      this.status.isshow = false;
    },
    //清空
    empty() {
      this.form = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 2,
        ishot: 2,
        status: 1,
      };
      //二级分类的列表数据
      this.secondCateList = [];
      //规格属性的列表
      this.attrsArr = [];
    },
    // 添加
    async add() {
      // 3.7 发送数据之前处理数据
      //   添加之前specsattr 后端要字符串数组，前端界面是多选，需要是数组。所以需要转换一下，再发送。
      //   需要拷贝，但是因为有文件，所以不能使用JSON.parse(JSON.stringify()),否则会丢失文件

      let data = {
        ...this.form,
        specsattr: JSON.stringify(this.form.specsattr),
        description: this.editor.txt.html(),
      };
      //发请求
      let res = await reqgoodsadd(data);
      this.checkeddata().then(() => {
        if (res.data.code === 200) {
          // 弹成功
          successAlert(res.data.msg);
          // 数据清空
          this.empty();
          // 弹框消失
          this.status.isshow = false;
          // // // 列表刷新----------此处调用vuex的方法------------------
          this.reqList();
        }
      });
    },
    //验空
    checkeddata() {
      return new Promise((reslove) => {
        if (this.form.first_cateid == "") {
          errorAlert("一级分类不能为空");
          return;
        }
        if (this.form.second_cateid == "") {
          errorAlert("二级分类不能为空");
          return;
        }
        if (this.form.goodsname == "") {
          errorAlert("商品名称不能为空");
          return;
        }
        if (this.form.price == "") {
          errorAlert("商品价格不能为空");
          return;
        }
        if (this.form.market_price == "") {
          errorAlert("市场价格不能为空");
          return;
        }

        if (this.form.img == "") {
          errorAlert("图片不能为空");
          return;
        }
        if (this.form.description == "") {
          errorAlert("商品描述不能为空");
          return;
        }
        if (this.form.specsid == "") {
          errorAlert("规格不能为空");
          return;
        }
        if (this.form.specsattr == "") {
          errorAlert("规格属性不能为空");
          return;
        }
        reslove();
      });
    },
    //7.3点击了编辑按钮 ，获取一条数据
    async getOne(id) {
      let res = await reqgoodsinfo({ id: id });
      this.checkeddata().then(() => {
      if (res.data.code == 200) {
        /* {"first_cateid":36,"second_cateid":40,"goodsname":"欧莱雅黑精华面膜",
        "price":1,"market_price":2,"img":"/uploads/eb636200-3dfa-11ec-8e2a-45d701821f79.jpeg",
        "description":"123","specsid":8,"specsattr":"白色,红色,绿色","isnew":2,"ishot":2,"status":1}
       */
        // 赋值给form
        this.form = res.data.list;
        // 补id
        this.form.id = id;
        // 修改upload-img组件的img
        this.$refs.upload.changeImg(this.$pre + this.form.img);
        //规格属性改为数组
        this.form.specsattr = JSON.parse(this.form.specsattr);

        //根据一级分类的选择，请求二级分类的列表，二级分类不重置的
        this.requst_second_cate_list();

        // 根据商品规格，计算商品属性列表，但是选中的商品属性不变的
        this.computed_show_attr();

        //editor opened之后才会有
        /*
        动画：2s
        发请求：1s 3s
          1s: editor undefined  2s,动画结束赋值 editor.txt.html(form.description)
          3s: editor 有了  2s，editor有了，form.description=""  editor.txt.html(form.description);   3s 数据回来了，editor.txt.html(form.description)
        */
        //给编辑器赋值
        if (this.editor) {
          this.editor.txt.html(this.form.description);
        }
      }
      })
    },
    //8.1修改逻辑
    async update() {
      let res = await reqgoodsedit({
        ...this.form,
        specsattr: JSON.stringify(this.form.specsattr),
      });
      if (res.data.code == 200) {
        successAlert(res.data.msg);
        this.empty();
        this.status.isshow = false;
        this.reqList();
      }
    },
    // 9.弹框关闭
    closed() {
      // 如果是添加的取消，什么都不做；如果是编辑的取消，form清空
      if (!this.status.isAdd) {
        this.empty();
      }
    },
  },
  computed: {
    ...mapGetters({
      //分类的列表数据
      cateList: "cate/list",
      //规格的列表数据
      specsList: "specs/list",
    }),
  },
  watch: {},
};
</script>
<style scoped lang="less">
@import "../../../less/index.less";
</style>
